package cn.edu.scnu.springbootcinema.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class AlipayService {

    @Value("${alipay.app_id}")
    private String appId;

    @Value("${alipay.merchant_private_key}")
    private String privateKey;

    @Value("${alipay.alipay_public_key}")
    private String publicKey;

    @Value("${alipay.return_url}")
    private String returnUrl;

    /**
     * 创建支付宝支付订单
     * @param outTradeNo 商户订单号
     * @param amount 金额
     * @param subject 商品标题
     */
    public String createOrder(String outTradeNo,
                              String amount,
                              String subject) throws AlipayApiException {
        AlipayClient client = new DefaultAlipayClient(
                "https://openapi-sandbox.dl.alipaydev.com/gateway.do",
                appId,
                privateKey,
                "json",
                "UTF-8",
                publicKey,
                "RSA2");

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setReturnUrl(returnUrl);

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", outTradeNo);
        bizContent.put("total_amount", amount);
        bizContent.put("subject", subject);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

        request.setBizContent(bizContent.toString());
        return client.pageExecute(request).getBody();
    }
}